/* eslint-disable no-undef */

/**
 * 网络监控相关API说明
 * @class
 */
function NetworkMonitoring() {
    if (navigator && navigator.onLine) {
        this.online = navigator.onLine;
    } else if (!navigator && wx && wx.getNetworkType) {
        var that = this;
        wx.getNetworkType({
            success(res) {
                that.online = res.networkType
            }
        })
    }
}

/**
 * 开启网络状况监控
 */
NetworkMonitoring.prototype.start = function (cb) {
    if (!navigator && wx && wx.onNetworkStatusChange) {
        wx.onNetworkStatusChange(function (res) {
            console.log(res.isConnected);
            console.log(res.networkType);
            if (res.isConnected) {
                cb('online');
            } else {
                cb('offline');
            }
        })
    } else {
        if (this.offlineEvent) {
            window.removeEventListener("offline", this.offlineEvent);
        } else {
            this.offlineEvent = () => {
                this.online = false;
                cb('offline');
            };
        }
        if (this.onlineEvent) {
            window.removeEventListener("online", this.onlineEvent);
        } else {
            this.onlineEvent = () => {
                this.online = true;
                cb('online');
            };
        }
        window.addEventListener("offline", this.offlineEvent);
        window.addEventListener("online", this.onlineEvent);
        this.online = navigator.onLine;
    }
}

/**
 * 移除网络状况变化监控
 */
NetworkMonitoring.prototype.stop = function () {
    if (!navigator && wx && wx.offNetworkStatusChange) {
        wx.offNetworkStatusChange(function (res) {
            console.log(res);
        })
    } else {
        window.removeEventListener("offline", this.offlineEvent);
        window.removeEventListener("online", this.onlineEvent);
        this.online = navigator.onLine;
    }
}

export {
    NetworkMonitoring
};
